#!/bin/bash

function uploadPictures {
	#uploadPictures $folderPath $picasaPictures $localAlbum
	folderPath=`echo $1` 		#path of just the folder with no beginning /
	localAlbum=`echo $2`		#the name of the local folder we are treating like an album
	localPictureCount=`echo $3`	#the number of pictures local

	#split large albums (greater than 1000 pictures) into multiple subfolders, then call the createAlbum function again.
	localAlbumPictureCount=$localPictureCount
	albumCount=1

	if [ $localAlbumPictureCount -gt 999 ]; then
		#bulldoze the pictures into subfolders

		#initial
		mkdir "./$folderPath/$localAlbum $albumCount"
		counter=1

		#move pictures
		ls -1 ./$folderPath/ | grep -E ".jpg|.JPG|.jpeg|.JPEG" | while read localPicture
		do
			if [ $counter -le 999 ]; then
				#echo moving  ./$folderPath/$localPicture to ./$folderPath/$localAlbum $albumCount
				mv "./$folderPath/$localPicture" "./$folderPath/$localAlbum $albumCount/$localPicture"
			else
				albumCount=$(($albumCount + 1))
				localAlbumPictureCount=$(($localAlbumPictureCount - $counter))
				mkdir "./$folderPath/$localAlbum $albumCount"
				counter=1
			fi

			#increment counter
			counter=$(($counter + 1 ))
		done

		#call loadFolder on this thing now that it has subfolders.
		loadFolder "$folderPath"

	fi

	#grab the pictures in the album
        echo "Querying Picasa album for pictures"
        picasaPictures=$(google picasa list --title $localAlbum --fields name)

        #get a count of picasa pictures
        for picasaPicture in $picasaPictures
        do
                picasaPictureCount=`expr $picasaPictureCount + 1`
        done

	#calculate the difference
	difference=`expr $localPictureCount - $picasaPictureCount`


	#loop through files in folder and compare
	ls -1 ./$folderPath/ | grep -E ".jpg|.JPG|.jpeg|.JPEG" | while read localPicture
	do
		#TODO: either change this or the grep above to look at the characters
		#	after the last period.
                #some program though it would be a good idea to store meta data about
                #a picture in the same named file with a .file at the end.
		checkJunk=`echo $localPicture | grep -E ".file" | wc -l`
		if [ $checkJunk -eq 0 ]
		then
			#make a variable that will store the full path (without the /)
			path=`echo "$folderPath/$localPicture"`

			#clean picture file to no spaces since googlecl sucks with spaces
			tmpExists=`echo 0`
			checkSpaces=`echo $path | grep -o " " | wc -l`
			if [ $checkSpaces -gt 0 ]
			then
				#copy file to a new name with no spaces and stick it in a tmp path
				oldPath=`echo $path`
				newPath=`echo $path | tr ' ' '_' | tr ',' '-'  `
				newPath=`echo tmp/$newPath`
				oldFolderPath=`echo $folderPath`
				newFolderPath=`echo $folderPath | tr ' ' '_' | tr ',' '-' `
				newFolderPath=`echo tmp/$newFolderPath`
				oldLocalPicture=`echo $localPicture`
				newLocalPicture=`echo $localPicture | tr ' ' '_' | tr ',' '-' `

				#double check to make sure we aren't doing any extra work here
				if [ "$path" != "$newPath" ]
				then
					path=`echo $newPath`
					localPicture=`echo $newLocalPicture`
					folderPath=`echo $newFolderPath`
				else
					checkSpaces=`echo 1`
				fi
			fi

			#check to see if picture already exists in picasa
			pictureExists=`echo 0`
			if [ $picasaPictureCount -gt 0 ]
			then
				for picasaPicture in $picasaPictures
				do
					if [ "$picasaPicture" == "$localPicture" ]
					then
						pictureExists=`echo 1`
					fi
				done
			fi

			#if it doesn't exist, then upload it
			if [ $pictureExists -eq 0 ]
			then
				echo "................"

				#copy the file path to the tmp directory.  we will store there for the upload (to get rid of spaces)
				if [ $checkSpaces -gt 0 ]
				then
					echo Moving $oldPath to $path
					echo Making directory ./$folderPath
					mkdir -p "./$folderPath"
					echo Copying file $localPicture to $folderPath
					cp "./$oldPath" "./$path"
					tmpExists=`echo 1`
				fi

				#make the attempt
				googleAttempt=$(google picasa post "$localAlbum" ./$path)

				#catch errors (TODO: NOT WORKING DAMNIT!)
				if [ "$?" -ne "0" ]; then
					echo $googleAttempt > /var/log/picasaSync/error.log
				fi

				uploadCount=$(expr $uploadCount + 1)
				remaining=$(expr $difference - $uploadCount)

				#echo the work left to do if pictures remain
				if [ $remaining -gt 0 ]
				then
					echo "  ...picture $localPicture uploaded successfully $remaining remaining"
				fi

			else
				picturesFound=`echo 1`
			fi

			#Remove tmp data and rest path, localPicture and folderPath
			if [ $checkSpaces -gt 0 ]
			then
				#remove tmp
				if  [ $tmpExists -gt 0 ] 
				then
					echo "Removing ./$newPath"
					rm ./$newPath
				fi

				path=`echo $oldPath`
				localPicture=`echo $oldLocalPicture`
				folderPath=`echo $oldFolderPath`
			fi


		fi
	done
	if [ $picturesFound -eq 0 ]
        then
       	        echo "$localAlbum has been completely uploaded to Picasa"
       	fi

}

function createAlbum {
	# $1 will hold the path


	#get folder information for the rest of this beast
	caFolderPath=`echo $1`
	depth=`echo $caFolderPath | grep -o "/" | wc -l`
	depth=`expr $depth + 1`
	localAlbum=`echo $caFolderPath | cut -d "/" -f$depth`

	#test if folder has pictures
	localPictureCount=`ls -1 ./$caFolderPath | grep -E ".jpg|.JPG|.jpeg|.JPEG" | cut -d "." -f2 | wc -l`

	#remove crap from the calc
	localPictureCountCrap=`ls -1 ./$caFolderPath | grep -E ".jpg.|.JPG.|.jpeg.|.JPEG." | cut -d "." -f2 | wc -l`
	localPictureCount=`expr $localPictureCount - $localPictureCountCrap`

	#check if there are pictures in this album, if not, gtfo.
	if [ "$localPictureCount" == "0" ]
	then
		echo "Folder $caFolderPath has no pictures, moving on..."
	else
		echo "Folder $caFolderPath contains $localPictureCount pictures"

		picturesFound=0
		picasaPictureCount=0
		uploadCount=0

		#test if album exists
		albumExists=0
		echo "Querying picasa for album $localAlbum"
		albumtest=`google picasa list-albums --title "$localAlbum"`
		if [ -n "$albumtest" ]
		then
		        albumExists=1
		fi

		#now the real deal. If it does not exist, add it then add all pictures indescriminately.
		#if it does exist, grab the pics from the album, compare file names, and add where they are missing.
		if [ $albumExists -eq 0 ]
		then
			echo "Album $localAlbum does not exist"

			#create the album
		        googleAttempt=`google picasa create $localAlbum --access "Private"`

		        #sometimes googlecl throws up. Catch the vomit here
		        if [ "$?" -ne "0" ]; then
		                echo $googleAttempt > /var/log/picasaSync/error.log
		        fi

			echo $googleAttempt
		else
			echo "FOUND: Album $localAlbum exists"

		fi

		uploadPictures "$caFolderPath" "$localAlbum" "$localPictureCount"
	fi

}

function loadFolder {
	#check for pictures, if found, upload this album
	#check for subfolders, if found, call this function again

	#grab inputs
	lfFolderPath=$1
	folderDepth=$2

	#check for jpg's
	pictures=`ls -1 ./$lfFolderPath/ | grep -E ".jpg|.JPG|.jpeg|.JPEG" `
	if [ -n pictures ]
	then
		if [ "$lfFolderPath" != "tmp" ]
		then
			#echo "Attempting upload of $lfFolderPath"
			createAlbum "$lfFolderPath"
		fi
	fi

	#linebreak so we can see where the process starts up again.
	echo "----------------------------------------------------------------------------------------------------------------"

	#recursively grab any subfolders
	subfolders=`ls -p ./$lfFolderPath/ | grep "/"`
	for subfolder in $subfolders
	do

		subfolder=$(echo $subfolder | cut -d "/" -f1 )

		#Some program stuck some thumbnails directly in subfolders of my pictures, essentially pissing right in my pool.
		#this is to prevent those from making it into picasa and fouling up my beautiful web albums with crappy thumbnails.
		periodPos=$(expr index "$subfolder" ".")

		if [ $periodPos -gt 0 ]; then
			echo "subfolder $subfolder will be skipped as it contains a period."
		else

			echo "Found subfolder $lfFolderPath/$subfolder"

			#store the current filepath so we can continue on without getting all choked up on our variables
			case $folderDepth in
				1)	path1=$(echo $lfFolderPath);;
				2)	path2=$(echo $lfFolderPath);;
				3)	path3=$(echo $lfFolderPath);;
				4)	path4=$(echo $lfFolderPath);;
				5)	path5=$(echo $lfFolderPath);;
			esac

			#increment the depth (this is a recursive function and is unfortunately necessary as a new shell isn't generated upon function call)
			folderDepth=$(($folderDepth + 1))

			loadFolder "$lfFolderPath/$subfolder" $folderDepth

			#reset the lfFolderPath and depth
			folderDepth=$(($folderDepth - 1))
			case $folderDepth in
				1)	lfFolderPath=$(echo $path1);;
				2)      lfFolderPath=$(echo $path2);;
				3)      lfFolderPath=$(echo $path3);;
				4)      lfFolderPath=$(echo $path4);;
				5)      lfFolderPath=$(echo $path5);;
			esac
		fi
	done


}

#modding the ifs to not use spaces so we don't get stuck on them, further modification is done to help googlecl with the same problem.
ORIGINAL_IFS=$IFS
IFS=$'\n'
ls -p | grep "/" | while read folder;
do
        folderPath=${folder%%/};
	folderDepth=1
        loadFolder $folderPath $folderDepth
done
IFS=$ORIGINAL_IFS
